const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const Joi = require('joi')

const appOptions = {
  port: 3000,
  host: '127.0.0.1'
}

const app = express();

// 文件上传
const multer = require('multer')
const upload = multer({
  dest: './public/upload'
})
app.use(upload.any())

// 静态资源托管
app.use(express.static('./public'));


// 全局挂载cors
app.use(cors())

// extended:false 表示返回数组和字符串  true 时返回任意类型
app.use(bodyParser.urlencoded({
  extended: false
}))

app.use(bodyParser.json())

// 统一做错误处理
app.use((req, res, next) => {
  // status=0 表示成功  status=1 表示失败  默认status=1
  res.cc = function (err, status = 1) {
    res.send({
      status,
      // 判断err是否为对象，否则是字符
      message: err instanceof Error ? err.message : err
    })
  }
  next();
})

const jwtconfig = require('../jwt_config/index')
const {
  expressjwt: jwt
} = require('express-jwt')
// app.use(jwt({
//   secret: jwtconfig.jwtSecretKey,
//   algorithms: ['HS256']
// }).unless({
//   path: [/^\/api\//]
// }))




// 引入登录模块路由
const loginRouter = require('../router/login')
app.use('/api', loginRouter)

// 引用用户路由
const userRouter = require('../router/userInfo')
app.use('/user', userRouter)

// 引用系统设置路由
const setRouter = require('../router/setting')
app.use('/set', setRouter)

// 引用产品路由
const productRouter = require('../router/product')
app.use('/pro', productRouter)

// 引用信息路由
const messageRouter = require('../router/message')
app.use('/msg', messageRouter)

// 引用文件路由
const fileRouter = require('../router/file')
app.use('/file', fileRouter)

// 引用登录日志路由
const loginLogRouter = require('../router/login_log')
app.use('/log', loginLogRouter)

// 引用操作日志路由
const operateLogRouter = require('../router/operation_log')
app.use('/log', operateLogRouter)

// 引用系统概览路由
const overviewRouter = require('../router/overview')
app.use('/overview', overviewRouter)

// 引用系统概览路由
const departMsgRouter = require('../router/department_msg')
app.use('/depart', departMsgRouter)

// 引用动态路由路由
const menuRouter = require('../router/menu')
app.use('/menu', menuRouter)

// 对不符合joi规则的请求进行拦截
app.use((err,req, res, next) => {
  if (err instanceof Joi.ValidationError) {
    // return res.cc(err)
    res.send({
      status: 1,
      message:'输入的数据不符合验证规则'
    })
  }
})

app.listen(appOptions.port, appOptions.host, () => {
  console.log('listening on port:' + appOptions.port);
})